# -*- coding: utf-8 -*-
from flask.views import View
from flask.helpers import url_for, flash
from werkzeug.utils import redirect
from werkzeug.exceptions import abort

from sys2do import app
from sys2do.setting import DEBUG
from sys2do.model import DBSession

__all__ = ['BasicView']

class BasicView( View ):
    template_folder = None

    methods = ['GET', 'POST']

    _debug = app.logger.debug
    _info = app.logger.info
    _error = app.logger.error

    def default( self ):  return url_for( '.view', action = 'index' )

    def dispatch_request( self, action ):
        if DEBUG:
            return self._despatchDebug( action )
        else:
            return self._despatchLive( action )


    def _despatchDebug( self, action ):
        return getattr( self, action )()

    def _despatchLive( self, action ):
        try:
            return getattr( self, action )()
        except AttributeError:
            abort( 404 )
        except:
            abort( 500 )



    #===========================================================================
    # blinker signal function ,for test and future use.
    #===========================================================================
    '''
    @property
    def namespace(self):
        from blinker import Namespace
        if not hasattr(self, '__namespace'): self.__namespace = Namespace()      
        return self.__namespace

    def getSignal(self,name):
        return self.namespace.signal(name)
    '''

@app.before_request
def before_request():    # occur before the request
    DBSession()


@app.teardown_request
def teardown_request( param ):    # if error occur on the controller
    DBSession.remove()    # to cleare the nested rollback


@app.after_request
def after_request( response ):
    return response
